﻿using System;
using Pharmacy.Data;
using Pharmacy.Ultilities;
using Pharmacy.Data.Core;

namespace Pharmacy.Business
{
    /// <summary>
    /// Provides a abstract layer between consumer and data layers.
    /// This should contain most of code related to business flows.
    /// </summary>
    public abstract class BaseBusiness : IDisposable
    {
        /// <summary>
        /// Gets the context to the merchant database.
        /// </summary>
        protected IObjectContext PharmacyContext { get; private set; }

        /// <summary>
        /// Gets the <see cref="ILockingControl"/> instance of this business object.
        /// </summary>
        protected ILockingControl LockingControl { get; private set; }

        /// <summary>
        /// Initializes new instance of <see cref="BaseBusiness"/>.
        /// </summary>        
        protected BaseBusiness()
        {
            if(PharmacyContext == null)
                PharmacyContext = ObjectContextFactory.CreatePharmacyContext(Global.UserName, Global.CurrentConnectionString);
            // create new locking control
            LockingControl = new PessimisticLocking(PharmacyContext);
        }

        /// <summary>
        /// Initializes new instance of <see cref="BaseBusiness"/>.
        /// </summary>
        /// <param name="masterContext">
        /// Reference to an existing data context of mater database.
        /// This is an optional parameter.
        /// </param>
        /// <param name="merchantContext">
        /// Reference to an existing data context of merchant database.
        /// This is an optional parameter.
        /// </param>
        protected BaseBusiness(IObjectContext pharmacyContext = null)
        {
            // assign database contexts
            PharmacyContext = pharmacyContext;
            // create new locking control
            LockingControl = new PessimisticLocking(PharmacyContext);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            // release all lock created in this business object
            LockingControl.UnLockAll();
            LockingControl.Dispose();
            // close database connection, if any
            if (PharmacyContext != null)
            {
                PharmacyContext.Dispose();
            }            
        }
    }
}
